import json
from urllib.parse import urlencode
from urllib.request import Request
from urllib.request import ProxyHandler
from urllib.request import build_opener
from urllib.error import URLError
from urllib.request import urlopen
from urllib.request import install_opener
from urllib.request import HTTPHandler
from http.cookiejar import CookieJar
from urllib.request import HTTPCookieProcessor
from bs4 import BeautifulSoup
from catch.read_file import read

#step 1:登录微博，获取cookies

def get_login(proxy_add):
    url = 'https://passport.weibo.cn/sso/login'

    # 构建登录参数
    parm = {'username': 'junzhenggg@163.com', 'password': 'abc@123', 'savestate': 1, 'r': 'http://m.weibo.cn/',
            'ec': 0, 'entry': 'mweibo', 'mainpageflag': 1, 'pagerefer': '', 'wentry': '', 'loginfrom': '',
            'client_id': '', 'code': '', 'qq': '', 'hff': '', 'hfp': ''}
    data_parm = urlencode(parm).encode('utf-8')
    print("请求参数：", data_parm)

    # 设置请求头
    head = {'Accept': '*/*',
            # 'Accept-Encoding': 'gzip, deflate, br',
            # 'Accept-Language': 'zh-CN,zh;q=0.8',
            'Connection': 'keep-alive',
            'Content-Length': '166',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Host': 'passport.weibo.cn',
            'Origin': 'https://passport.weibo.cn',
            'Referer': 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F',
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36'}
    try:
        # 使用代理服务器
        proxy = ProxyHandler({'http': proxy_add})
        print('代理服务器：', proxy_add)

        # 使用cookies
        cookiesJar = CookieJar()

        request = Request(url=url, data=data_parm, headers=head)
        opener = build_opener(proxy, HTTPHandler(debuglevel=1), HTTPCookieProcessor(cookiejar=cookiesJar))
        install_opener(opener)
        respon = urlopen(request).read().decode("utf-8")
        # data = json.loads(respon)
        print(respon)

        cook_file = open('../file/cookies.txt', 'w')
        for item in cookiesJar:
            print(item.name + '=' + item.value)
            cook_file.write(item.name + '=' + item.value + ';')

    except URLError as e:
        if hasattr(e, 'code'):
            print(e.code)
        if hasattr(e, 'reason'):
            print(e.reason)


if __name__ == '__main__':
    ip = read()
    get_login(ip)
